package com.dididoctor.patient.Activity.Usercentre.Userinfo;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.dididoctor.patient.Activity.GlobalParams;
import com.dididoctor.patient.MV.EduActivity;
import com.dididoctor.patient.R;
import com.dididoctor.patient.Ui.NoScrollGridView;
import com.dididoctor.patient.Ui.cityList.CharacterParser;
import com.dididoctor.patient.Ui.cityList.CityBean;
import com.dididoctor.patient.Ui.cityList.CityListAdapter;
import com.dididoctor.patient.Ui.cityList.PinyinComparator;
import com.dididoctor.patient.Ui.cityList.SideBar;
import com.dididoctor.patient.Utils.ABAppUtil;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @version 2.0
 * @类描述：
 * @项目名称：ddgh
 * @类名称： EditCityActivity
 * @包名称： com.dididoctor.patient.Activity.Usercentre.Userinfo
 * @创建人： liying
 * @创建时间：16/4/14 14:10
 * @修改人：
 * @修改时间：16/4/14 14:10
 * @修改备注:编辑城市界面
 */
public class EditCityActivity extends EduActivity implements EditCityView, SideBar.OnTouchingLetterChangedListener, TextWatcher {
    private LinearLayout mLayKeyWord, mLayKeyWordInput;
    private NoScrollGridView mGridHotCity;
    private HotCityAdapter mHotCityAdapter;
    private ListView mListCity;
    private SideBar mSideCity;
    private CharacterParser characterParser;//汉字转换拼音
    private PinyinComparator pinyinComparator;//根据拼音来排列ListView里面数据
    private List<CityBean> sortDataList = new ArrayList<CityBean>();
    private CityListAdapter mCityAdapter;
    private ArrayList<CityBean> hotCity = new GlobalParams().hotCityData;

    //搜索浮层
    private Button mBtnCancelKeyWord;
    private EditText mEtKeyWord;
    private ListView mLvKeyWordCity;
    private CityListAdapter mKeyWordAdapter;
    private List<CityBean> keyWordDataList = new ArrayList<CityBean>();

    @Override
    public void init() {

        //实例化主界面
        initView();

        //实例话头部布局
        initHead();
    }

    @Override
    public void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.lay_keyword:
                mLayKeyWord.setVisibility(View.GONE);
                mLayKeyWordInput.setVisibility(View.VISIBLE);
                ABAppUtil.showSoftInput(EditCityActivity.this, mEtKeyWord);
                break;
            case R.id.btn_cancel_keyword:
                mLayKeyWord.setVisibility(View.VISIBLE);
                mLayKeyWordInput.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    public void setContentLayout() {
        setContentView(R.layout.activity_edit_city);
    }


    private void initHead() {
        ((TextView) findViewById(R.id.tv_title)).setText("城市选择");

    }

    private void initView() {
        mLayKeyWord = (LinearLayout) findViewById(R.id.lay_keyword);
        mLayKeyWord.setOnClickListener(this);
        mLayKeyWordInput = (LinearLayout) findViewById(R.id.lay_keyword_input);
        mBtnCancelKeyWord = (Button) findViewById(R.id.btn_cancel_keyword);
        mBtnCancelKeyWord.setOnClickListener(this);
        LinearLayout headView = (LinearLayout) LayoutInflater.from(EditCityActivity.this).inflate(R.layout.headview_citylist, null);
        mGridHotCity = (NoScrollGridView) headView.findViewById(R.id.gri_hot_city);
        mGridHotCity.setIsIntercept(false);
        mHotCityAdapter = new HotCityAdapter(EditCityActivity.this, hotCity);
        mGridHotCity.setAdapter(mHotCityAdapter);
        mListCity = (ListView) findViewById(R.id.lv_city);
        mListCity.addHeaderView(headView);
        mSideCity = (SideBar) findViewById(R.id.sidebar_city);
        mSideCity.setOnTouchingLetterChangedListener(this);

        //实例化数据
        initData();

        //搜索浮层
        mEtKeyWord = (EditText) findViewById(R.id.et_keyword);
        mLvKeyWordCity = (ListView) findViewById(R.id.lv_keyword_city);
        mKeyWordAdapter = new CityListAdapter(this, keyWordDataList);
        mLvKeyWordCity.setAdapter(mKeyWordAdapter);
        mEtKeyWord.addTextChangedListener(this);

    }

    @Override
    public void finishActivity() {
        EditCityActivity.this.finish();
    }

    @Override
    public void onTouchingLetterChanged(String s) {
        int position = 0;
        //该字母首次出现的位置
        if (mCityAdapter != null) {
            position = mCityAdapter.getPositionForSection(s.charAt(0));
        }
        if (position != -1) {
            mListCity.setSelection(position);
        }
    }

    public void initData() {
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator();


        getData();
        fillData(sortDataList);
        // 根据a-z进行排序源数据
        Collections.sort(sortDataList, pinyinComparator);
        mCityAdapter = new CityListAdapter(this, sortDataList);
        mListCity.setAdapter(mCityAdapter);

    }

    /**
     * 填充数据
     *
     * @param list
     */
    private void fillData(List<CityBean> list) {
        for (CityBean cUserInfoDto : list) {
            if (cUserInfoDto != null && cUserInfoDto.getName() != null) {
                String pinyin = characterParser.getSelling(cUserInfoDto.getName());
                String suoxie = CharacterParser.getFirstSpell(cUserInfoDto.getName());

                cUserInfoDto.setSuoxie(suoxie);
                String sortString = pinyin.substring(0, 1).toUpperCase();

//                if ("1".equals(cUserInfoDto.getUtype())) {// 判断是否是管理员
//                    cUserInfoDto.setSortLetters("☆");
//                } else
                if (sortString.matches("[A-Z]")) {// 正则表达式，判断首字母是否是英文字母
                    cUserInfoDto.setSortLetters(sortString);
                }
//                else {
//                    cUserInfoDto.setSortLetters("#");
//                }
            }
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        filterData(s.toString(), sortDataList);
    }

    @Override
    public void afterTextChanged(Editable s) {

    }


    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr, List<CityBean> list) {
        List<CityBean> filterDateList = new ArrayList<CityBean>();

        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = keyWordDataList;
        } else {
            filterDateList.clear();
            for (CityBean sortModel : list) {
                String name = sortModel.getCityName();
                String suoxie = sortModel.getSortLetters();
                if (name.indexOf(filterStr.toString()) != -1 || suoxie.indexOf(filterStr.toString()) != -1 || characterParser.getSelling(name).startsWith(filterStr.toString())) {
                    filterDateList.add(sortModel);
                }
            }
        }

        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        mKeyWordAdapter.updateListView(filterDateList);
    }

    public void getData() {
        try {
            InputStream open = EditCityActivity.this.getResources().getAssets().open("cityList.xml");
            XmlParser(open);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void XmlParser(InputStream in) {
        CityBean cityBean = null;
        String pinYin = "";
        XmlPullParserFactory factory;
        try {
            factory = XmlPullParserFactory.newInstance();
            factory.setNamespaceAware(true);
            XmlPullParser xpp = factory.newPullParser();
            xpp.setInput(in, "UTF-8");
            int evtType = xpp.getEventType();
            // 一直循环，直到文档结束
            while (evtType != XmlPullParser.END_DOCUMENT) {
                switch (evtType) {
                    case XmlPullParser.START_TAG:
                        if (xpp.getName().equals("keys")) {
                            pinYin = xpp.nextText();
                        } else if (xpp.getName().equals("dict")) {
                            cityBean = new CityBean();
                            cityBean.setSortLetters(pinYin);
                        } else if (xpp.getName().equals("string") && cityBean.getCityCode() == null) {
                            cityBean.setCityCode(xpp.nextText());
                        } else if (xpp.getName().equals("string") && cityBean.getCityName() == null) {
                            cityBean.setCityName(xpp.nextText());
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        if (xpp.getName().equals("dict")) {
                            sortDataList.add(cityBean);
                        }
                        break;

                    default:
                        break;
                }
                evtType = xpp.next();

            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }
}